/**
 * 目标：实现session (支持中文值)
 * npm i koa-session
 */
const Koa = require('koa')
const app = new Koa()

/**
 * koa-session
 * 初始化
 */
const session = require('koa-session')

app.keys = ['some secret hurr']

const CONFIG = {
  key: 'koa:sess', //cookie key (default is koa:sess) 
  maxAge: 86400000, // cookie 的过期时间 maxAge in ms (default is 1 days) 
  overwrite: true, //是否可以 overwrite (默认 default true) 
  httpOnly: true, //cookie 是否只有服务器端可以访问 httpOnly or not (default true) signed: true, //签名默认 true 
  rolling: false, //在每次请求时强行设置 cookie，这将重置 cookie 过期时间（默认：false） 
  renew: false, //(boolean) renew session when session is nearly expired, 
}

app.use(session(CONFIG, app))


/**
 * 路由
 */
const Router = require('koa-router')

const index = new Router()
index.get('/', async (ctx, next) => {
  ctx.session.username = '张三'
  ctx.body = 'set session ok'
  await next()
})
const user = new Router()
index.get('/user', async (ctx, next) => {
  ctx.body = `<h2>${ctx.session.username}</h2>`
  await next()
})

const router = new Router()
router.use(index.routes(), index.allowedMethods())
router.use(user.routes(), user.allowedMethods())

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('服务器在127.0.0.1:3000运行中...')
})